#include <iostream>
#include <string>
using namespace std;

#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int main()
{
    int fds[2] = {0};
    // 1. 创建管道
    int n = pipe(fds); // fds输出形参数
    if (n == -1)
    {
        cerr << "pipe fail" << endl;
        return 1;
    }

    // 2. 创建子进程
    pid_t id = fork();
    if (id < 0)
    {
        return 2;
    }
    if (id == 0)
    {
        // child
        // 3. 关闭read
        ::close(fds[0]);

        int count = 0;
        while (true)
        {
            string messages = "hello pipe ";
            messages += to_string(getpid());
            messages += ",";
            messages += to_string(count);
            // 开始通信
            ::write(fds[1], messages.c_str(), messages.size());
            count++;
            sleep(1);
        }
        exit(0);
    }
    else
    {
        // father
        //  关闭write
        ::close(fds[1]);
        char buffer[1024];
        while(true)
        {
            size_t n = ::read(fds[0],buffer,1024);
            if(n > 0)
            {
                buffer[n] = '\0';
                cout << "child->father,message:" << buffer << endl;
            }
        }
        pid_t rid = waitpid(id, nullptr, 0);
        cout << "father wait child success,rid:" << rid << endl;
    }

    return 0;
}